package com;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.util.Date;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;

public class ExportUitls {

	/**
	 * @Title: saveAndOut
	 * @Description: 保存并输出Excel表格
	 * @param @param the(二维数组)
	 * @param @param fileName(文件名称)
	 * @param @param request
	 * @param @param response
	 * @param @throws IOException
	 * @date 2017年5月8日 下午2:39:00
	 * @return void
	 * @throws
	 */
	public static void saveAndOut(String[][] the,String fileName, HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		// TODO Auto-generated method stub
		// 文件存储路径
		String storePath = request.getServletContext().getRealPath("/export");
		System.out.println(storePath);
		Date date = new Date();
		DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM);
		String s = df.format(date);
		//String file_name = s + "bill.xls";
		String file_name = s + fileName+".xls";
		File f = new File(storePath + "\\" + file_name);
		File ff = new File(storePath);
		if (!ff.exists()) {
			ff.mkdirs();// 创建多级目录，mkdir只创建一级目录
		}

		WritableWorkbook workbook = Workbook.createWorkbook(f);
		WritableSheet sheet = workbook.createSheet("sheet1", 0);
		Label lab = null;
		for (int i = 0; i < the.length; i++) {
			for (int j = 0; j < the[i].length; j++) {
				lab = new Label(j, i, the[i][j]); // Label(col,row,str);
				try {
					sheet.addCell(lab);
				} catch (WriteException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		workbook.write();
		try {
			workbook.close();
		} catch (WriteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		/* 如果文件存在 */
		if (f.exists()) {
			String filename = URLEncoder.encode(f.getName(), "utf-8");
			response.reset();
			response.setContentType("application/x-msdownload");
			response.addHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
			int fileLength = (int) f.length();
			response.setContentLength(fileLength);
			/* 如果文件长度大于0 */
			if (fileLength != 0) {
				/* 创建输入流 */
				InputStream inStream = new FileInputStream(f);
				byte[] buf = new byte[4096];
				/* 创建输出流 */
				ServletOutputStream servletOS = response.getOutputStream();
				int readLength;
				while (((readLength = inStream.read(buf)) != -1)) {
					servletOS.write(buf, 0, readLength);
				}
				inStream.close();
				servletOS.flush();
				servletOS.close();
			}
		}
	}
}
